import { initGlobalState as qiankunInitGlobalState, MicroAppStateActions } from 'qiankun'
import type { App } from 'vue'

// 定义全局状态类型
export interface GlobalState {
  user: any | null
  token: string
  menu: Array<any>
  breadcrumb: Array<{ name: string, path?: string }>
  [key: string]: any
}

// 全局状态管理实例变量
let globalStateActions: MicroAppStateActions | null = null
let currentState: GlobalState | null = null

/**
 * 初始化全局状态管理
 * @param initialState 初始状态
 * @returns 全局状态管理实例
 */
export function initGlobalState(initialState: GlobalState) {
  // 如果实例已存在，直接返回
  if (globalStateActions) {
    return globalStateActions
  }

  // 使用qiankun的initGlobalState方法初始化全局状态
  const state = qiankunInitGlobalState(initialState)
  currentState = { ...initialState }

  // 从localStorage恢复状态（如果有）
  const savedState = localStorage.getItem('microFrontendGlobalState')
  if (savedState) {
    try {
      const parsedState = JSON.parse(savedState)
      state.setGlobalState({ ...currentState, ...parsedState })
    } catch (e) {
      console.error('Failed to restore global state from localStorage', e)
    }
  }

  /**
   * 增强的全局状态监听方法
   * @param callback 状态变化回调函数
   * @param fireImmediately 是否立即触发回调
   */
  const enhancedOnGlobalStateChange = (callback: (state: GlobalState, prevState: GlobalState) => void, fireImmediately?: boolean) => {
    return state.onGlobalStateChange((newState: GlobalState, prevState: GlobalState) => {
      // console.log('[GlobalState] Changed:', prevState, '->', newState)
      currentState = { ...newState }
      // 持久化关键状态
      if (newState.token || newState.user) {
        try {
          localStorage.setItem('microFrontendGlobalState', JSON.stringify({
            user: newState.user,
            token: newState.token
          }))
        } catch (e) {
          console.error('Failed to save global state to localStorage', e)
        }
      }
      callback(newState, prevState)
    }, fireImmediately)
  }

  /**
   * 增强的全局状态设置方法
   * @param partial 要更新的部分状态
   */
  const enhancedSetGlobalState = (partial: Partial<GlobalState>) => {
    console.log('[GlobalState] Update:', partial)
    return state.setGlobalState(partial)
  }

  // 保存全局实例引用
  globalStateActions = {
    onGlobalStateChange: enhancedOnGlobalStateChange,
    setGlobalState: enhancedSetGlobalState
  }

  return globalStateActions
}

/**
 * 获取全局状态管理实例
 * @returns 全局状态管理实例，如果未初始化则返回null
 */
export function getGlobalStateActions(): MicroAppStateActions | null {
  return globalStateActions
}

/**
 * 获取当前全局状态
 * @returns 当前全局状态，如果未初始化则返回null
 */
export function getCurrentState(): GlobalState | null {
  return currentState
}

/**
 * 重置全局状态
 * @param newState 新的全局状态
 */
export function resetGlobalState(newState?: GlobalState): void {
  if (globalStateActions) {
    const resetState = newState || {
      user: null,
      token: '',
      menu: [],
      breadcrumb: []
    }
    globalStateActions.setGlobalState(resetState)
  }
}

/**
 * 将全局状态管理方法注入到Vue应用实例
 * @param app Vue应用实例
 */
export function provideGlobalStateToVue(app: App): void {
  if (globalStateActions) {
    app.config.globalProperties.$globalState = {
      onGlobalStateChange: globalStateActions.onGlobalStateChange,
      setGlobalState: globalStateActions.setGlobalState,
      getCurrentState
    }
  }
}

/**
 * 监听全局状态变化
 * @param callback 状态变化回调函数
 * @param fireImmediately 是否立即触发回调
 */
export function onGlobalStateChange(callback: (state: GlobalState, prevState: GlobalState) => void, fireImmediately?: boolean) {
  if (!globalStateActions) {
    console.error('Global state not initialized. Call initGlobalState first.')
    return () => { }
  }
  return globalStateActions.onGlobalStateChange(callback, fireImmediately)
}

/**
 * 设置全局状态
 * @param partial 要更新的部分状态
 */
export function setGlobalState(partial: Partial<GlobalState>) {
  if (!globalStateActions) {
    console.error('Global state not initialized. Call initGlobalState first.')
    return false
  }
  return globalStateActions.setGlobalState(partial)
}

// 导出类型供微应用使用
export type { MicroAppStateActions } from 'qiankun'